<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #canvas {
      box-shadow: 2px 4px 6px #eee;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
</body>
<script src="/script/utils.js"></script>
<script src="/components/Arc.js"></script>
<script src="/components/Ball.js"></script>
<script>
  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')
  
  const W = canvas.width = 702
  const H = canvas.height = 486

  let mouse = C.getOffset(canvas)

  // canvas.onclick = function () {
  //   console.log(mouse.x, mouse.y)
  // }

  const cx = W / 2
  const cy = H / 2
  const br = 22
  const r = 220
  const endAngle = Math.atan2(r / 2, r / 2)
  const lineWidth = 22
  let dx = 0, dy = 0
  let isMoveDown = false
  let grd = ctx.createLinearGradient(cx - r - lineWidth, cy - r - lineWidth, cx + r + lineWidth, cy + r + lineWidth)
  grd.addColorStop(0, '#08ACE8')
  grd.addColorStop(1, '#2AF396')

  const ball = new Ball({
    x: cx + r,
    y: cy,
    r: br,
    fillStyle: '#FFFFFF',
    shadowColor: '#CFCACA',
    shadowBlur: 4,
    shadowOffsetY: 2,
  }).render(ctx)

  const arcFront = new Arc({
    r: r,
    lineWidth,
    endAngle: Math.atan2(ball.y - cy, ball.x - cx),
    translateX: cx,
    translateY: cy,
    strokeStyle: grd
  }).render(ctx)

  const arcBack = new Arc({
    r: r,
    lineWidth,
    endAngle,
    translateX: cx,
    translateY: cy,
    strokeStyle: '#D8D8D8'
  }).render(ctx)

  canvas.addEventListener('mousedown', function (e) {
    if (ball.isPoint(mouse)) {
      isMoveDown = true
      dx = mouse.x - ball.x
      dy = mouse.y - ball.y
      canvas.addEventListener('mousemove', moveBallFn)
      canvas.addEventListener('mouseup', upBallFn)
    }
  })
  function moveBallFn() {
    let angle = Math.atan2(mouse.y - cy, mouse.x - cx)
    let val = parseInt(C.toAngle(angle) / 15)
    console.log(val)
    // if (angle >= C.toRad(45) && angle < C.toRad(90)) {
    //   angle = C.toRad(45)
    // }
    // if (angle <= C.toRad(135) && angle >= C.toRad(90)) {
    //   angle = C.toRad(135)
    // }
      arcFront.endAngle = angle
      ball.x = Math.cos(angle) * r + cx
      ball.y = Math.sin(angle) * r + cy
    // if (parseInt(C.toAngle(angle)) % 15 === 0) {
    // } else {
    //   // upBallFn()
    // }
  }
  function upBallFn() {
    isMoveDown = false
    canvas.removeEventListener('mousemove', moveBallFn)
    canvas.removeEventListener('mouseup', upBallFn)
  }

  function drawFrame() {
    window.requestAnimationFrame(drawFrame)
    ctx.clearRect(0, 0, W, H)

    arcBack.render(ctx)
    arcFront.render(ctx)
    ball.render(ctx)
  }
  drawFrame()
</script>
</html>